//
//  UserInfoDetailViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "UserInfoDetailViewController.h"
#import "M13UserDefaults.h"
#import "GDataXMLNode.h"
#import "ELifeAppDelegate.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "GetMyData.h"
#import "UserInfoModel.h"
#import "LoginController.h"

@implementation UserInfoDetailViewController

@synthesize email, idCardNumber, phoneNumber, name;

UserInfoModel* userInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
        
    [phoneNumber release];
    [email release];
    [name release];
    [idCardNumber release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

-(void)initTextFields:(UITextField *)textField
{    
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = (textField == phoneNumber 
                              || textField == idCardNumber)
    ? UIKeyboardTypeNumberPad : UIKeyboardTypeDefault;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initTextFields:phoneNumber];
    [self initTextFields:email];
    [self initTextFields:idCardNumber];
    [self initTextFields:name];
    [self.navigationItem setTitle:@"用户资料"]; 
    
    NSArray* info = [M13UserDefaults getUserDefaultsArray:USERINFO_NAMEANDPASSWORD];
    if (info != nil && [info count] > 0){
        [phoneNumber setText:[info objectAtIndex:0]];
        [phoneNumber setEnabled:false];
    }
    
    userInfo = [UserInfoModel getInstance];
    [phoneNumber setText:userInfo.phone];
    [email setText:userInfo.email];
    [idCardNumber setText:userInfo.real_id];
    [name setText:userInfo.realname];
    
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (IBAction)closeKeypad:(id)sender
{
    [name resignFirstResponder];
    [email resignFirstResponder];
    [idCardNumber resignFirstResponder];
    [phoneNumber resignFirstResponder];
    
    [sender resignFirstResponder];
}
-(IBAction)cancel:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder];
	return YES;
}


- (void)search
{
    if ([name.text length] == 0 || [email.text length] == 0 || [idCardNumber.text length] == 0)
    {
        [AlertView showAlert:@"请填写完整信息"];
        return;
    }
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
    
//    请求地址: /user.php 417136
//    请求参数: action => updatebaseinfo
//    user_id => 用户id (必填)
//    以下至少传一项
//    phone	=> 手机
//    email	=> 邮件
//    realname  => 真实姓名
//    real_id   => 身份证号
//    bank_name => 提现银行 传拼音 (gongshang=>工商 zhaohang=>招商 jianshe=>建设 nongye=>农行 beijing=>北京 jiaotong=>交通)
//    bank_num  => 银行卡号
//    bank_province  => 银行所在省
//    bank_city  => 银行所在城市 
//    draw_pw   => 提现密码

    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"user.php"]];
    
    
    NSString* userName = [GetMyData getUserId];
    NSLog(@"UserName: ==== %@\n", userName);
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"updatebaseinfo" forKey:@"action"];
    [param setObject:userName forKey:@"user_id"];
    [param setObject:name.text forKey:@"realname"];
    [param setObject:email.text forKey:@"email"];
    [param setObject:idCardNumber.text forKey:@"real_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
}

- (void)iRequestFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"-----rootElement-----%@\n", rootElement);
    
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"-----headsElement-----%@\n", headsElement);
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert setTag:11];
        [alert release];
    } else if (code == -124){
        [AlertView showAlert:@"请填写真实姓名"];
    } else if (code != 0){
        [AlertView showAlert:@"修改失败"];
    } else {
        [AlertView showAlert:@"修改成功"];
    }
    
    [doc release];
    
}



-(IBAction)confirm:(id)sender
{
    //    [self.navigationController popViewControllerAnimated:YES];
    [self search];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1){
            LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
            
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
        return; 
        
    }
}
@end
